<template>
  <div class="setting">
    <div class="card">
      <el-table
        v-loading="listLoading"
        :data="departmentList"
        border
        stripe
      >
        <el-table-column label="序号" type="index" align="center" width="80" />
        <el-table-column label="部门名称" prop="name" align="center" />
        <el-table-column label="报餐人" prop="examineUsers" align="center">
          <template v-slot="{ row }">
            <el-popover
              placement="top-start"
              title="报餐人"
              width="200"
              trigger="click"
            >
              <el-button
                slot="reference"
                type="text"
              >
                查看
              </el-button>
              <template>
                <div>
                  <el-tag
                    v-for="item in row?.examineUsers"
                    :key="item.id"
                    style="margin: 0 10px 10px 0;"
                  >
                    {{ item?.user?.username }}
                  </el-tag>
                </div>
              </template>
            </el-popover>

          </template>
        </el-table-column>

        <el-table-column label="部门简介" prop="description" align="center">
          <template v-slot="{ row }">
            {{ row?.description ?? '-' }}
          </template>
        </el-table-column>

        <el-table-column label="操作" prop="description" align="center">
          <template v-slot="{ row }">
            <el-button type="primary" size="mini" @click="handleSetting(row)">设置报餐人</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <UserSelectModal
      v-model="isSelected"
      :visible.sync="selectedListVisible"
      :show-dept-select="false"
      :fetch-user-fn="customFetchUserFn"
      title="报餐人设置"
      @onConfirm="handleConfirm"
    />

  </div>
</template>

<script>
import { getUserByDepartmentParentId } from '@/api/basic'
import { getExamineUser, setExamineUser } from '@/api/repast'
import { getDept } from '@/api/v2/basic'
import UserSelectModal from '@/components/UserSelectModal/UserSelectModal.vue'
export default {
  name: '',
  components: {
    UserSelectModal
  },
  data() {
    return {
      departmentList: [],
      examineUsers: null,
      selectedListVisible: false,
      userList: [],
      currentDepartment: null,
      loading: false,
      isSelected: [],
      maxChoice: Infinity,
      load: false,
      listLoading: false
    }
  },

  computed: {
    userListFormat() {
      return this.userList?.map(item => {
        return {
          label: item?.user?.username,
          value: item?.user?.id
        }
      })
    }
  },

  created() {
    this.getExamineUser()
    // this.getDepartmentList()
  },

  methods: {
    async getExamineUser() {
      this.listLoading = true
      try {
        const res = await getExamineUser()
        this.examineUsers = res.data
        await this.getDepartmentList()
      } catch (error) {
        throw new Error(error?.response?.data?.message || '获取报餐人失败')
      } finally {
        this.listLoading = false
      }
    },

    async getDepartmentList() {
      try {
        const res = await getDept()
        this.departmentList = res.data.map(item => {
          return {
            ...item,
            examineUsers: this.examineUsers[item.id]
          }
        })
      } catch (error) {
        throw new Error(error?.response?.data?.message || '部门获取失败')
      }
    },

    async handleSetting(row) {
      console.log('row --------->', row)
      this.currentDepartment = row.id
      this.isSelected = row?.examineUsers ? row?.examineUsers.map(item => {
        return item?.user?.id
      }) : []
      this.selectedListVisible = true
    },

    handleConfirm(e) {
      const params = {
        user_id: JSON.stringify(e) ?? '',
        department_id: this.currentDepartment
      }

      if (this.isSetting()) {
        params.id = this.isSetting()
      }

      this.settingExamineUser(params)
    },

    isSetting() {
      const selectedUser = this.isSelected.find(item => item.department_id === this.currentDepartment)
      return selectedUser ? selectedUser.id : null
    },

    async settingExamineUser(params) {
      try {
        const res = await setExamineUser(params)
        this.$message.success('操作成功')
        this.refresh()
      } catch (error) {
        this.$message.error(error?.response?.data?.message || '操作失败')
      }
    },

    refresh() {
      this.getExamineUser()
    },

    async customFetchUserFn(params) {
      const res = await getUserByDepartmentParentId({
        ...params,
        department_id: this.currentDepartment,
        name: params.username
      })

      return {
        data: res.data.data.map(item => item.user),
        meta: {
          total: res.data.total
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.setting {
  padding: 20px;

  .card {
    border-radius: 4px;
    background-color: #fff;
    padding: 20px;
    margin-bottom: 30px;
  }
}
</style>
